#!/usr/bin/env python
# -*- coding: utf-8 -*-

from easygconf.gconfdict import GConfDict
import random
import os
from pysqlite2 import dbapi2 as sqlite

dirname = "/home/critter/brain-bacon/wallpaper-rotator/"
wallpapersdir = os.path.join(os.path.expanduser("~"), "pics/wallpaper/")

def randomize(wallpapers,dirname,gc,rotate_mode):
    if rotate_mode == "random":
        dice = random.randint(0,(len(wallpapers)-1))
        gc["picture_filename"] = dirname + wallpapers[dice][1]

    elif rotate_mode == "ordered":
        wall_num = (find_wallpaper(wallpapers,dirname,gc)-1)+1
        if wall_num > len(wallpapers)-1:
            wall_num = 0
        gc["picture_filename"] = dirname + wallpapers[wall_num][1]
        
    if wallpapers[find_wallpaper(wallpapers,dirname,gc)-1][2] == None:
        gc["picture_options"] = "scaled"
    else:
        gc["picture_options"] = wallpapers[find_wallpaper(wallpapers,dirname,gc)-1][2]
        
def find_wallpaper(wallpapers,dirname,gc):
    for count in xrange(0,len(wallpapers)):
        print(wallpapersdir + wallpapers[count][1])
        if wallpapersdir + wallpapers[count][1] == gc["picture_filename"]:
            return count+1
            
def load_wallpapers():
    connection = sqlite.connect(dirname + "wallpaper_db")
    cursor = connection.cursor()
    
    if os.path.isfile(dirname + "wallpaper_db") == False:
        wallpapers = [f for f in os.listdir(wallpapersdir)
            if os.path.isfile(os.path.join(wallpapersdir, f))]
        cursor.execute('CREATE TABLE wallpapers (id INTEGER PRIMARY KEY, name VARCHAR(50), display VARCHAR(50))')
        for count in wallpapers:
            cursor.execute('INSERT INTO wallpapers VALUES (null, ?, null)', (count,))
        connection.commit()
        
    cursor.execute('SELECT * FROM wallpapers')
    return cursor.fetchall()
    cursor.close()
    connection.close()
